const express = require('express')
const app = express()
const port = 3000

let cookieParser = require('cookie-parser');
let session = require('express-session');

app.use('/public', express.static('public'))
app.use(express.json())
app.use(cookieParser('sessiontest'));
app.use(session({
  secret: 'sessiontest',//与cookieParser中的一致
  resave: true,
  saveUninitialized: true
}));
app.post('/login', function (req, res, next) {
  let user = {
    name: req.body.username
  }
  // 把user保存在req的session属性里面
  req.session.user = user;
  res.status(200).json({
    sucess: true,
    msg: '登录成功'
  })
});
app.get('/home', function (req, res, next) {
  if (req.session.user) {
    let user = req.session.user;
    let name = user.name;
    res.send('你好' + name + '，欢迎来到我的家园。');
  } else {
    res.send('你还没有登录，先登录下再试试！');
  }
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))